package com.tencent.bk.sdk.iam.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.tencent.bk.sdk.iam.config.IamConfiguration;
import com.tencent.bk.sdk.iam.service.HttpClientService;
import com.tencent.bk.sdk.iam.util.JsonUtil;
import com.tencent.bk.sdk.iam.util.http.DefaultApacheHttpClientBuilder;
import org.apache.http.Consts;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class DefaultHttpClientServiceImpl implements HttpClientService {
    private static final Logger log = LoggerFactory.getLogger(DefaultHttpClientServiceImpl.class);
    private CloseableHttpClient httpClient;
    private IamConfiguration iamConfiguration;

    public DefaultHttpClientServiceImpl(IamConfiguration iamConfiguration) {
        this.iamConfiguration = iamConfiguration;
        DefaultApacheHttpClientBuilder defaultApacheHttpClientBuilder = DefaultApacheHttpClientBuilder.get();
        //实验性设置
        defaultApacheHttpClientBuilder.setMaxTotalConn(2000);
        defaultApacheHttpClientBuilder.setMaxConnPerHost(1000);
        httpClient = defaultApacheHttpClientBuilder.build();
    }

    public String doHttpGet(String uri) {
        HttpGet getRequest = new HttpGet(this.buildUrl(uri));
        this.buildAuthHeader(getRequest);
        return this.doExecuteRequest(getRequest);
    }

    public String doHttpPost(String uri, Object body) {
        HttpPost postRequest = new HttpPost(this.buildUrl(uri));

        try {
            String jsonBody = JsonUtil.toJson(body);
            log.debug("Post request, uri:{}, body:{}", uri, jsonBody);
            postRequest.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
        } catch (JsonProcessingException var5) {
            log.warn("Json encode failed!|{}|{}", new Object[]{uri, body, var5});
            return null;
        }

        this.buildAuthHeader(postRequest);
        return this.doExecuteRequest(postRequest);
    }

    public String doHttpPut(String uri, Object body) {
        HttpPut putRequest = new HttpPut(this.buildUrl(uri));

        try {
            String jsonBody = JsonUtil.toJson(body);
            log.debug("Put request, uri:{}, body:{}", uri, jsonBody);
            putRequest.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
        } catch (JsonProcessingException var5) {
            log.warn("Json encode failed!|{}|{}", new Object[]{uri, body, var5});
            return null;
        }

        this.buildAuthHeader(putRequest);
        return this.doExecuteRequest(putRequest);
    }

    public String doHttpDelete(String uri) {
        HttpDelete deleteRequest = new HttpDelete(this.buildUrl(uri));
        this.buildAuthHeader(deleteRequest);
        return this.doExecuteRequest(deleteRequest);
    }

    private String doExecuteRequest(HttpRequestBase request) {
        try {
            CloseableHttpResponse response = this.httpClient.execute(request);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseString = response.getEntity() == null ? null : EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                log.debug("Http response|{}|{}", statusCode, responseString);
                return responseString;
            }

            log.warn("Http response is null!");
        } catch (IOException var5) {
            log.error("Error while executing http request!", var5);
        } finally {
            //新增
            request.releaseConnection();
        }

        return null;
    }

    private String buildUrl(String uri) {
        return this.iamConfiguration.getIamBaseUrl() + uri;
    }

    private void buildAuthHeader(HttpRequestBase httpRequest) {
        httpRequest.setHeader("X-Bk-App-Code", this.iamConfiguration.getAppCode());
        httpRequest.setHeader("X-Bk-App-Secret", this.iamConfiguration.getAppSecret());
    }
}
